package com.zxm.sunshineaiary.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.style.ImageSpan;

import com.zxm.sunshineaiary.info.DateInfo;

public class CharsUtil {

	private static final int YEAR = 1900;

	/**
	 * dp转px
	 * 
	 * @param dipValue
	 * @return
	 */
	public static int dipTopx(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	private static StorageFile mStorageFile = StorageFile.getInsance();

	/**
	 * 获得图片的姓名和姓名在String中的位置
	 * 
	 * @param s
	 * @param i
	 * @param str
	 */
	public static void getImageName(ArrayList<String> s, ArrayList<Integer> i,
			String str) {
		Pattern p = Pattern.compile("\\[(.*?)\\]");
		Matcher m = p.matcher(str);
		while (m.find()) {
			s.add(m.group(1));
			int start = m.start();
			i.add(start);
		}
	}

	/**
	 * 
	 * @param mDateInfo
	 *            日期
	 * @param ss
	 *            EditText的Spannbale对象
	 * @param text
	 * @return
	 * @throws IOException
	 */
	public static CharSequence getImageName(DateInfo mDateInfo, Spannable ss,
			CharSequence text) throws IOException {
		Pattern p = Pattern.compile("\\[(.*?)\\]");
		Matcher matcher = p.matcher(text);
		while (matcher.find()) {
			String imagePath = mStorageFile.getFilePath(mDateInfo, matcher
					.group(1), mStorageFile.PNG);

			Drawable drawble = Drawable.createFromPath(imagePath);

			int drawableH = drawble.getMinimumHeight();
			int drawableW = drawble.getMinimumWidth();
			drawble.setBounds(5, 0, drawableW + 5, drawableH);
			ImageSpan imageSpan = new ImageSpan(drawble, matcher.group(1)
					+ ".png", ImageSpan.ALIGN_BASELINE);

			ss.setSpan(imageSpan, matcher.start(), (matcher.end()),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return ss;
	}

	/**
	 * 把日期转成"yyyy-MM-dd"的格式
	 * 
	 * @param year
	 * @param month
	 * @param day
	 * @return
	 */
	public static String stringToDate(int year, int month, int day) {
		Date date = new Date(year - YEAR, month-1, day);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String s = sdf.format(date);
		return s;
	}

	/**
	 * 把传入的String转化成加0的格式：08，07
	 * 
	 * @param date
	 * @return
	 */
	public static String accountDateString(int date) {
		if (date < 10) {
			return ("0" + date);
		}
		return date + "";
	}
}
